//
// Created by martin on 5/1/22.
//

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <errno.h>

int printOpenMax()
{
    // 方式一: sysconf 获取 _SC_OPEN_MAX
    long openMax = sysconf(_SC_OPEN_MAX);
    if (openMax == -1) {
        perror("sysconf OPEN_MAX error");
        return -1;
    }
    printf("openMax = %ld\n", openMax);

    // 方式二: getrlimit 获取 RLIMIT_NOFILE
    struct rlimit limit;
    if (getrlimit(RLIMIT_NOFILE, &limit) == -1) {
        perror("getrlimit RLIMIT_NOFILE error");
        return -1;
    }
    printf("soft limit = %ld, hard limit = %ld\n", limit.rlim_cur, limit.rlim_max);
    return 0;
}

int main()
{
    printOpenMax();

    // setrlimit 修改系统限制RLIMIT_NOFILE (用户级文件描述符数限制)
    struct rlimit limit;
    limit.rlim_cur = 2048;
    limit.rlim_max = 4096; // 注意不要大于 前面已经读取出来的rlim_max (4096)
    int ret = setrlimit(RLIMIT_NOFILE, &limit);
    if (ret == -1) {
        perror("setrlimit error");
        return -1;
    }

    printOpenMax();
    return 0;
}


